package com.ndp.fb.walle.controller;

import com.alibaba.fastjson.JSON;
import com.ndp.fb.enums.ErrorType;
import com.ndp.fb.exception.BusinessException;
import com.ndp.fb.rdb.model.User;
import com.ndp.fb.walle.business.UserAudienceTemplateService;
import com.ndp.fb.walle.model.vo.OutputResult;
import com.ndp.fb.walle.model.vo.useraudiencetemplate.param.UserAudienceTemplateVoParam;
import com.ndp.fb.walle.util.ResponseUtils;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by yeahmobi on 2015/3/19.
 */
@RequestMapping("/useraudiencetemplates")
@Controller
public class UserAudienceTemplateController {
    /**
     * LOG日志
     */
    private final org.slf4j.Logger LOG = LoggerFactory.getLogger(getClass());
    @Autowired
    private UserAudienceTemplateService userAudienceTemplateService;

    /**
     * 保存用户定位模板
     * @param param
     * @param httpServletRequest
     * @return
     */
    @RequestMapping(value = "save")
    @ResponseBody
    public ResponseEntity<String> save(@RequestParam(value = "param", required = true) String param, HttpServletRequest httpServletRequest) {
    	ErrorType errorType = null;
        Map<String, Object> data = null;
        try {
            UserAudienceTemplateVoParam userAudienceTemplateVoParam = JSON.parseObject(param, UserAudienceTemplateVoParam.class);
            User user = (User) httpServletRequest.getSession().getAttribute("user");
            //这里设置为公司ID
            userAudienceTemplateVoParam.setCompanyId(user.getOrgId());
            Long id = userAudienceTemplateService.saveUserAudienceTemplate(user.getTicket(), userAudienceTemplateVoParam);

            data = new HashMap<String, Object>();
            data.put("id", id);
        } catch (BusinessException e) {
            errorType = e.getErrorType();
            LOG.info("UserAudienceTemplateController->save", e);
        } catch (Exception e) {
            errorType = ErrorType.INTERNAL_EXCEPTION;
            LOG.error(e.getMessage(), e);
        }
        OutputResult outputResult = ResponseUtils.bulidOutputResult(errorType, data);
        return ResponseUtils.returnJsonWithUTF8(JSON.toJSONString(outputResult));
    }

    /**
     * 根据产品查找受众模板
     * @param prodId
     * @return
     */
    @RequestMapping(value = "findByProd")
    public List<String> findBySite(@RequestParam(required = true) Long prodId) {
        return null;// TODO: 2016/4/22 impl
    }

}
